package com.zhentao.service;

import com.zhentao.dto.AiConversationDTO;
import com.zhentao.dto.CreateConversationRequest;
import com.zhentao.entity.AiConversation;
import com.zhentao.repository.AiConversationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * AI会话管理服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AiConversationService {
    
    private final AiConversationRepository conversationRepository;
    private final AiMessageService messageService;
    
    /**
     * 创建新的AI会话
     */
    @Transactional
    public AiConversationDTO createConversation(CreateConversationRequest request) {
        log.info("创建AI会话，用户ID: {}, 标题: {}", request.getUserId(), request.getTitle());
        
        // 生成唯一的会话ID
        String conversationId = generateConversationId();
        
        // 如果没有提供标题，生成默认标题
        String title = request.getTitle();
        if (title == null || title.trim().isEmpty()) {
            title = "新对话 " + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"));
        }
        
        // 创建会话实体
        AiConversation conversation = new AiConversation(
            request.getUserId(),
            conversationId,
            title
        );
        
        conversation.setDescription(request.getDescription());
        conversation.setTags(request.getTags());
        
        // 保存会话
        AiConversation saved = conversationRepository.save(conversation);
        
        // 如果有初始消息，创建消息记录
        if (request.getInitialMessage() != null && !request.getInitialMessage().trim().isEmpty()) {
            messageService.saveUserMessage(
                request.getUserId(),
                conversationId,
                request.getInitialMessage().trim()
            );
            
            // 更新会话的最后消息信息
            saved.updateLastMessage(request.getInitialMessage().trim());
            conversationRepository.save(saved);
        }
        
        log.info("AI会话创建成功，会话ID: {}", conversationId);
        return convertToDTO(saved);
    }
    
    /**
     * 获取用户的会话列表
     */
    public Page<AiConversationDTO> getUserConversations(Integer userId, int page, int size, boolean includeArchived) {
        log.info("获取用户会话列表，用户ID: {}, 页码: {}, 大小: {}", userId, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size, 
            Sort.by(Sort.Direction.DESC, "lastMessageTime", "updateTime"));
        
        Page<AiConversation> conversations;
        if (includeArchived) {
            conversations = conversationRepository.findAllConversationsByUserId(userId, pageable);
        } else {
            conversations = conversationRepository.findActiveConversationsByUserId(userId, pageable);
        }
        
        return conversations.map(this::convertToDTO);
    }
    
    /**
     * 根据会话ID获取会话详情
     */
    public Optional<AiConversationDTO> getConversationById(Integer userId, String conversationId) {
        log.info("获取会话详情，用户ID: {}, 会话ID: {}", userId, conversationId);
        
        Optional<AiConversation> conversation = conversationRepository
            .findByUserIdAndConversationId(userId, conversationId);
        
        return conversation.map(this::convertToDTO);
    }
    
    /**
     * 更新会话标题
     */
    @Transactional
    public boolean updateConversationTitle(Integer userId, String conversationId, String newTitle) {
        log.info("更新会话标题，用户ID: {}, 会话ID: {}, 新标题: {}", userId, conversationId, newTitle);
        
        Optional<AiConversation> optionalConversation = conversationRepository
            .findByUserIdAndConversationId(userId, conversationId);
        
        if (optionalConversation.isPresent()) {
            AiConversation conversation = optionalConversation.get();
            conversation.setTitle(newTitle);
            conversation.setUpdateTime(LocalDateTime.now());
            conversationRepository.save(conversation);
            return true;
        }
        
        return false;
    }
    
    /**
     * 删除会话
     */
    @Transactional
    public boolean deleteConversation(Integer userId, String conversationId) {
        log.info("删除会话，用户ID: {}, 会话ID: {}", userId, conversationId);
        
        Optional<AiConversation> optionalConversation = conversationRepository
            .findByUserIdAndConversationId(userId, conversationId);
        
        if (optionalConversation.isPresent()) {
            AiConversation conversation = optionalConversation.get();
            conversation.delete();
            conversationRepository.save(conversation);
            
            // 同时删除相关的消息记录
            messageService.deleteMessagesByConversationId(conversationId);
            
            return true;
        }
        
        return false;
    }
    
    /**
     * 归档会话
     */
    @Transactional
    public boolean archiveConversation(Integer userId, String conversationId) {
        log.info("归档会话，用户ID: {}, 会话ID: {}", userId, conversationId);
        
        Optional<AiConversation> optionalConversation = conversationRepository
            .findByUserIdAndConversationId(userId, conversationId);
        
        if (optionalConversation.isPresent()) {
            AiConversation conversation = optionalConversation.get();
            conversation.archive();
            conversationRepository.save(conversation);
            return true;
        }
        
        return false;
    }
    
    /**
     * 置顶/取消置顶会话
     */
    @Transactional
    public boolean togglePinConversation(Integer userId, String conversationId) {
        log.info("切换会话置顶状态，用户ID: {}, 会话ID: {}", userId, conversationId);
        
        Optional<AiConversation> optionalConversation = conversationRepository
            .findByUserIdAndConversationId(userId, conversationId);
        
        if (optionalConversation.isPresent()) {
            AiConversation conversation = optionalConversation.get();
            conversation.togglePin();
            conversationRepository.save(conversation);
            return true;
        }
        
        return false;
    }
    
    /**
     * 更新会话的最后消息信息
     */
    @Transactional
    public void updateLastMessage(String conversationId, String lastMessage) {
        Optional<AiConversation> optionalConversation = conversationRepository
            .findByConversationId(conversationId);
        
        if (optionalConversation.isPresent()) {
            AiConversation conversation = optionalConversation.get();
            conversation.updateLastMessage(lastMessage);
            conversationRepository.save(conversation);
        }
    }
    
    /**
     * 搜索会话
     */
    public Page<AiConversationDTO> searchConversations(Integer userId, String keyword, int page, int size) {
        log.info("搜索会话，用户ID: {}, 关键词: {}", userId, keyword);
        
        Pageable pageable = PageRequest.of(page - 1, size, 
            Sort.by(Sort.Direction.DESC, "lastMessageTime"));
        
        Page<AiConversation> conversations = conversationRepository
            .findConversationsByUserIdAndTitleContaining(userId, keyword, pageable);
        
        return conversations.map(this::convertToDTO);
    }
    
    /**
     * 生成唯一的会话ID
     */
    private String generateConversationId() {
        return "ai_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
    
    /**
     * 转换为DTO
     */
    private AiConversationDTO convertToDTO(AiConversation conversation) {
        AiConversationDTO dto = new AiConversationDTO();
        dto.setId(conversation.getId());
        dto.setUserId(conversation.getUserId());
        dto.setConversationId(conversation.getConversationId());
        dto.setTitle(conversation.getTitle());
        dto.setDescription(conversation.getDescription());
        dto.setCreateTime(conversation.getCreateTime());
        dto.setUpdateTime(conversation.getUpdateTime());
        dto.setLastMessageTime(conversation.getLastMessageTime());
        dto.setLastMessage(conversation.getLastMessage());
        dto.setMessageCount(conversation.getMessageCount());
        dto.setStatus(conversation.getStatus());
        dto.setPinned(conversation.getPinned());
        dto.setTags(conversation.getTags());
        return dto;
    }
}
